import React,{useEffect,useState} from 'react';
import {
    SafeAreaView,
    StyleSheet,
    ScrollView,
    View,
    Text,
    DeviceEventEmitter, TextInput, TouchableOpacity, Keyboard, Image,
} from 'react-native';
import Header from '../../widgets/Header';
import {cutZero, getffly, numMulti, setTextThousand} from '../../utils/common';
import screen from '../../utils/screen';
import {useStores} from '../../store';
import {observer} from 'mobx-react';
import {LGBtn} from '../../widgets/buttons';
import RequestUtil from '../../utils/RequestUtil';
import Api from '../../utils/Api';
import {AppModal} from '../../widgets/modal';
import AppEvent from '../../utils/AppEvent';
import Constants from '../../utils/Constants';
import RefreshFlatList, {RefreshState} from '../../widgets/RefreshFlatList';
import ShadowBoxView from '../../widgets/ShadowBoxView';
import Images from '../../images/Images';

const pageSize = 10

export default observer( ({navigation})=>{


    const {userStore} = useStores()

    const [data,setData] = useState([])
    const [alldata,setAllata] = useState(null)
    const [page,setPage] = useState(1)
    const [refreshState,setRefreshState] = useState(RefreshState.Idle)

    useEffect(()=>{

        getData()
    },[])

    useEffect(()=>{
        if(!alldata) return
        if(page === 1) return;
        if(page * pageSize < alldata.length){
            setRefreshState(RefreshState.FooterRefreshing)
            setTimeout(()=>{
                let newlist = []
                let startIndex = data.length
                for(let i = startIndex; i < page * pageSize;i++){
                    newlist.push(alldata[i])
                }
                setData(data.concat(newlist))
                setRefreshState(RefreshState.Idle)
            },1000)
        }else{
            setRefreshState(RefreshState.NoMoreData)
        }

    },[page])

    const getData = ()=>{
        AppModal.showLoading()

        RequestUtil.get(Api.myInvest).then(res=>{
            AppModal.hideTip()
            let list = res.data.list
            if(!list.length){
                setAllata(list)
                setRefreshState(RefreshState.EmptyData)
                return
            }

            if(pageSize * page > list.length){
                setData(list)
            }else{
                let newlist = []
                for(let i = 0;i < pageSize * page;i++){
                    if(list[i]){
                        newlist.push(list[i])
                    }
                }
                console.log('new list',newlist)
                setData(newlist)
            }
            setAllata(list)
        },error=>{
            console.log(error)
            AppModal.hideTip()
            AppModal.showTip(error.msg)
        })
    }



    const renderItem = ({item,index})=>{
        console.log(item)

        return (
            <View style={{padding:screen.PIXEL_40,paddingVertical:screen.PIXEL_20}}>
                <ShadowBoxView
                    shadowOption={{
                        radius:screen.PIXEL_40,
                        color:'#000',
                        x:0,
                        y:0,
                        border:5
                    }}
                >
                    <TouchableOpacity
                        activeOpacity={1}
                        style={{backgroundColor: '#fff', padding:screen.PIXEL_40,borderRadius:screen.PIXEL_40}}
                        onPress={()=>{
                            navigation.push('InvestmentDetail',{id:item.id})
                        }}
                    >
                        <Text style={{color:'#000',fontSize:12}}>{item.product_name}</Text>
                        <View style={{marginTop:screen.PIXEL_20,flexDirection:'row'}}>
                            <View style={{flex:1}}>
                                <Text style={{color:'#000',fontSize:12}}>{Constants.account.starting_amount}</Text>
                                <Text style={{fontSize:30,color:'#FF7012'}}>{setTextThousand(Number(item.amount) )}</Text>
                            </View>

                            <View style={{flex:1}}>
                                <Text style={{color:'#000',fontSize:12}}>{Constants.account.cycle}</Text>
                                <Text style={{fontSize:15,color:'#FF7012'}}>{item.cycle + ' days'}</Text>
                            </View>

                        </View>

                        <View style={{marginTop:screen.PIXEL_20,flexDirection:'row'}}>
                            <View style={{flex:1}}>
                                <Text style={{color:'#000',fontSize:12}}>{Constants.account.interest}</Text>
                                <Text style={{fontSize:15,color:'#FF7012'}}>{numMulti(item.interest,100) + '%'}</Text>
                            </View>

                            <View style={{flex:1}}>
                                <Text style={{color:'#000',fontSize:12}}>{Constants.account.profit}</Text>
                                <Text style={{fontSize:30,color:'#FF7012'}}>{`${Constants.appsymbol} ${setTextThousand(cutZero(item.profit))}`}</Text>
                            </View>

                        </View>

                        <Text style={{color:'#000',fontSize:13}}>{Constants.account.start_date}</Text>
                        <Text style={{color:'#999',fontSize:13}}>{item.start_time}</Text>
                        <Text style={{color:'#000',fontSize:13}}>{Constants.account.redemption_date}</Text>
                        <Text style={{color:'#999',fontSize:13}}>{item.end_time}</Text>

                        <View style={[styles.statusBg,{backgroundColor: item.status === 'cancelled' ? '#C1C1C1' : '#FD7315' }]}>
                            <Text style={{fontSize:13 ,color:'#fff'}}>{item.status}</Text>
                        </View>

                    </TouchableOpacity>

                </ShadowBoxView>
            </View>
        )
    }


    return (
        <View style={styles.container}>
            <Header title={Constants.account.my_investment} navigation={navigation}/>

            {
                alldata && (
                    <RefreshFlatList
                        data={data}
                        renderItem={renderItem}
                        refreshState={refreshState}
                        onFooterRefresh={()=>{
                            setPage(page + 1)
                        }}
                        onHeaderRefresh={()=>{
                            setPage(1)
                            getData()
                        }}
                        footerEmptyDataComponent={
                            <View style={{ height:screen.PIXEL_400,justifyContent:'center', alignItems: 'center'}}>
                                <Image
                                    source={ Images.empty}
                                    resizeMode={'contain'}
                                    style={{ width:screen.PIXEL_200, height: screen.PIXEL_200 }}
                                />
                                <Text style={{fontFamily:getffly("regular"), color: '#A6C4C3', fontSize: 14, marginTop: screen.PIXEL_30 }}>{Constants.team.no_record}</Text>
                            </View>
                        }
                    />
                )
            }



        </View>
    )
})

const styles= StyleSheet.create({
    container:{
        flex:1,backgroundColor:'#fff'
    },
    content:{
        flex:1,
        paddingHorizontal:screen.PIXEL_60
    },
    statusBg: {
        position:'absolute',top:0,right:0,width:screen.PIXEL_220,
        height:screen.PIXEL_60,backgroundColor:'#FD7315',
        justifyContent: 'center',alignItems:'center',
        borderTopLeftRadius:screen.PIXEL_20,
        borderBottomLeftRadius: screen.PIXEL_20,
        borderTopRightRadius:screen.PIXEL_40
    }

})
